var config = require('./../../config.json');
var uid = require('uid');
var nameSpace = config.redisNamespace;
var authorUrl = config.authorUrl;
var redis = require('redis');
var User = require('./../../Model/User.js');

module.exports = function(req, res, next) {
    var uid = req.cookies.uid || null;
    var username = req.cookies.userName || "";
    var redisClient = redis.createClient();
    var redirectUrl = '/login?' + encodeURI(req.url.replace(/^\//, ''));
    if (uid && username) {
        redisClient.get(nameSpace + ':user:' + uid, (function(req, res, next) {
            return function(err, reply) {
                redisClient.quit();
                var user = JSON.parse(reply); //给user赋值
                if (err || !reply || JSON.parse(reply).userName.toLowerCase() !== username.toLowerCase()) {
                    res.redirect(redirectUrl);
                } else {
                    var extend = require('extend');
                    user.uid = uid;
                    req.user = extend(new User(), user); //将user传递给下面的中间件
                    next();
                }
            };
        })(req, res, next));
    } else {
        res.clearCookie('userName');
        res.clearCookie('uid');
        console.log('cookies not vialid, redirect to login page!');
        res.redirect(redirectUrl);
    }
};